const { chapterModel, userModel, courseModel, chapter_opened } = require('../../model');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const { getResultToObject, getResultToObjectComplete } = require('../../services/utils');

module.exports = {
  list: function (req,res) {
    const { org, account } = req.decode;
    const user_attr = ['org'];
    const chap_attr = ['id', 'order', 'series', 'name'];
    const user_where = { org: org, account: account };
    userModel.findByRelation(user_attr, user_where,{
      model: chapterModel.getModel(),
      attributes: chap_attr
    }).then(result => {
      const list = getResultToObject(result, 'chapter', chap_attr);
      res.send({
        code: 20000,
        data: {
          items: list,
          total: list.length
        }
      });
    }).catch(err => {
      console.log(err);
      res.send({
        code: 10000
      });
    })
  },
  listBySeries: function (req,res) {
    const { org, account } = req.decode;
    const { series } = req.query;
    const user_attr = ['org'];
    const chap_attr = ['id', 'series','order', 'name', 'page_url', 'map_url', 'points'];
    const user_where = { org: org, account: account };
    const chap_where = { series: series};
    userModel.findByRelation(user_attr, user_where,{
      model: chapterModel.getModel(),
      attributes: chap_attr,
      where: chap_where
    }).then(result => {
      const list = getResultToObject(result, 'chapter', chap_attr);
      if (list.length === 0) {
        return res.send({
          code: 20000,
          data: {
            items: [],
            total: 0
          }
        });
      }
      // TODO 改到前端排序
      list.sort(function (a, b) {
        return a.order - b.order;
      });
      return res.send({
        code: 20000,
        data: {
          items: list,
          total: list.length
        }
      });
    }).catch(err => {
      console.log(err);
      return res.send({
        code: 10000,
        message: '获取章节失败'
      });
    })
  },
  create: function (req,res) {
    const org = req.decode.org;
    const { series, total, name, page_url, map_url, points } = req.body;
    const config = {
      order: total + 1,
      org: org,
      series: series,
      name: name,
      page_url: page_url,
      map_url: map_url,
      points: points,
      updatedAt: Date.now(),
      createdAt: Date.now()
    };
    chapterModel.create(config).then(function () {
      res.send({
        code: 20000
      })
    }).catch(function (err) {
      console.log(err);
      res.send({
        code: 10000
      })
    })
  },
  delete: async (req,res) => {
    const org = req.decode.org;
    const { id, order, series } = req.body;

    try {
      const courseExist = await courseModel.findByFilter(['id'], {chapter: id});
      if (courseExist[0]) {
        return res.send({
          code: 10001, msg: `该章节还存在${courseExist.length}个关卡，请先删除关卡`
        })
      }
      await chapterModel.delete({id: id, org: org});
      await chapterModel.decrement('order',{
        series: series,
        org: org,
        order:{
          [Op.gt]: order
        }
      });
      return res.send({
        code: 20000,
        msg: '删除章节成功'
      });
    } catch (e) {console.log(e)}
  },
  update: function (req,res) {
    const org = req.decode.org;
    const { id, name, page_url, map_url, points } = req.body;
    const attributes = { name: name, page_url: page_url, map_url: map_url, points: points };
    const where = { id: id, org: org };
    chapterModel.update(attributes,where).then(function () {
      res.send({
        code: 20000
      })
    }).catch(function (err) {
      console.log(err);
      res.send({
        code: 10000
      })
    })
  },
  order: function (req,res) {
    const org = req.decode.org;
    const { current, target, curOrder, tarOrder } = req.body;

    chapterModel.update({ order: curOrder }, { id: current, org: org })
      .then(function (result) {
        chapterModel.update({ order: tarOrder }, { id: target, org: org }).then(function () {
          return res.send({
            code: 20000
          })
        })
    })
  }
};
